package com.ddd.demo.service.impl;

import com.ddd.demo.mapper.UserMapper;
import com.ddd.demo.domain.eo.User;
import com.ddd.demo.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    /**
     * TODO if you use mysql,please delete (required=false)
     */
    @Autowired(required=false)
    UserMapper userMapper;

    @Override
    public User findById(int id) {
        return userMapper.findById(id);
    }

    @Override
    public void insertBatch() {
        List<User> dataList = new ArrayList<User>();
        User user1 = new User();
        user1.setName("a");
        User user2 = new User();
        user2.setName("a");
        User user3 = new User();
        user3.setName("a");
        dataList.add(user1);
        dataList.add(user2);
        dataList.add(user3);

        if (null != dataList && dataList.size() > 0) {
            //the size to insert every time
            int pointsDataLimit = 1000;
            Integer size = dataList.size();
            // confirm if need to bach
            if (pointsDataLimit < size) {
                //batch number
                int part = size / pointsDataLimit;
                System.out.println("total ： " + size + " num，！" + " batch ：" + part + "num");
                for (int i = 0; i < part; i++) {
                    List<User> listPage = dataList.subList(0, pointsDataLimit);
                    System.out.println("num:" + (i + 1) + "times,running:" + listPage);
                    //insert
                    userMapper.insertBatch(listPage);

                    dataList.subList(0, pointsDataLimit).clear();
                }
                if (!dataList.isEmpty()) {
                    //the last data
                    System.out.println("the last data:" + dataList);
                    //insert
                    userMapper.insertBatch(dataList);
                }
            } else {
                System.out.println("not need to batch:" + dataList);
                //insert
                userMapper.insertBatch(dataList);
            }
        } else {
            System.out.println("not have data!!!");
        }
    }

    @Override
    public PageInfo<User> findUserPage(int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List<User> list = userMapper.findUserPage();
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

}

